import Aedes from 'aedes';
import { createServer } from 'net';
import { WebSocketServer, WebSocket } from 'ws';
const TCP_PORT = 1883;
const WS_PORT = 8083;

const useMqtt = () => {
  const aedes = new Aedes();
  // 支持 ​TCP 连接​，供 Node.js、Python 等非浏览器客户端使用
  const server = createServer(aedes.handle);
  const ws = new WebSocketServer({ port: WS_PORT });
  console.log(`🌐 MQTT Broker (WebSocket) 运行在 ws://localhost:${WS_PORT}`);

  // 支持 websocket 连接，供浏览器客户端使用
  ws.on('connection', (wsP) => {
    // 3. 将 WebSocket 连接转换为 Duplex 流
    const duplexStream = WebSocket.createWebSocketStream(wsP, { encoding: 'utf8' });

    // 4. 将流交给 Aedes 处理
    aedes.handle(duplexStream);
    // 监听客户端连接事件

    // 5. 错误处理
    duplexStream.on('error', (err) => {
      console.error('WebSocket 流错误:', err);
      ws.close();
    });
  });

  aedes.on('client', (client) => {
    console.log(`📡 客户端连接: ID=${client.id}`);
  });

  // 监听客户端断开事件
  aedes.on('clientDisconnect', (client) => {
    console.log(`❌ 客户端断开: ID=${client.id}`);
  });

  // 监听消息发布事件（忽略系统主题）
  aedes.on('publish', (packet) => {
    console.log(packet.payload.toString());
    if (!packet.topic.startsWith('$SYS')) {
      console.log(`✉️ 主题 [${packet.topic}] 收到消息: ${packet.payload.toString()}`);
    }
  });
  aedes.on('subscribe', (subscriptions, client) => {
    console.log(subscriptions, client);
  });

  aedes.on('clientError', () => {
    console.log('出错了');
  });

  server.listen(TCP_PORT, () => {
    console.log(`✅ MQTT Broker 运行在 tcp://localhost:${TCP_PORT}`);
  });
};

export default useMqtt;
